package com.csg.ses.service.ses.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csg.ses.common.utils.CommonUtil;
import com.csg.ses.common.utils.MybatisPlusUtil;
import com.csg.ses.dao.ses.SysEmployeeDao;
import com.csg.ses.dao.ses.SysRoleAccountsDao;
import com.csg.ses.dao.ses.SysUserLoginDao;
import com.csg.ses.entity.ses.SysEmployeeEntity;
import com.csg.ses.entity.ses.SysRoleAccountsEntity;
import com.csg.ses.entity.ses.SysUserLoginEntity;
import com.csg.ses.service.ses.SysEmployeeService;
import com.csg.ses.service.ses.SysRoleAccountsService;
import com.csg.ses.vo.common.IdListVo;
import com.csg.ses.vo.common.Result;
import com.csg.ses.vo.common.ResultStatus;
import com.csg.ses.vo.login.UserContext;
import com.csg.ses.vo.login.UserView;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Decoder;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 雇员
 * @author wangjun
 * @date 2020/11/16
 */
@Service
@RequiredArgsConstructor
public class SysEmployeeServiceImpl extends ServiceImpl<SysEmployeeDao, SysEmployeeEntity> implements SysEmployeeService {
    private final SysEmployeeDao sysEmployeeDao;
    private final SysUserLoginDao sysUserLoginDao;
    private final SysRoleAccountsDao sysRoleAccountsDao;

    @Override
    public Result retrieve(SysEmployeeEntity emp, Long current, Long size) {
        try {
            Page<SysEmployeeEntity> page = MybatisPlusUtil.initPage(current, size, true);
            QueryWrapper<SysEmployeeEntity> qw = new QueryWrapper();
            if (!CommonUtil.isEmpty(emp.getEmpName())) {
                qw.like("emp_name", emp.getEmpName());
            }
            qw.orderByAsc("emp_id");
            return new Result(sysEmployeeDao.retrieve(page, qw), ResultStatus.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultStatus.FAILED);
        }
    }

    @Override
    public SysEmployeeEntity getUserLoginEmp(String empId) {
        if (empId != null) {
            QueryWrapper<SysEmployeeEntity> queryWrapper = new QueryWrapper();
            queryWrapper.eq("emp_id", empId);
            return sysEmployeeDao.selectOne(queryWrapper);
        } else {
            return null;
        }
    }

    @Override
    public Result getById(String id) {
        if (!CommonUtil.isEmpty(id)) {
            return new Result(sysEmployeeDao.selectById(id), ResultStatus.SUCCESS);
        } else {
            throw new RuntimeException("id不能为空！");
        }
    }

    @Override
    public Result queryAllEmployee() {
        return new Result(sysEmployeeDao.getAllEmployee());
    }

    @Override
    @Transactional
    public boolean save(SysEmployeeEntity sysEmployee) {
        BASE64Decoder decoder = new BASE64Decoder();
        UserView userView = UserContext.getUserView();
        try {
            if (!CommonUtil.isEmpty(sysEmployee.getEmpId())) {
                SysEmployeeEntity countEmp = sysEmployeeDao.getByUserName(sysEmployee.getLoginCode());//根据用户名查询是否有人
                System.out.println(countEmp);
                if ((countEmp != null && countEmp.getEmpId().equals(sysEmployee.getEmpId())) || countEmp == null) {//修改人员校验
                    sysEmployee.setPassword(new String(decoder.decodeBuffer(sysEmployee.getPassword()))); //将base64加密的密码解成明文密码
                    SysEmployeeEntity user = sysEmployeeDao.selectById(sysEmployee.getEmpId());
                    if (!user.getPassword().equals(sysEmployee.getPassword())) {//如果密码不一致，才需要MD5加密
                        sysEmployee.setPassword(DigestUtils.md5DigestAsHex(sysEmployee.getPassword().getBytes())); //md5加密
                    }

                    sysEmployeeDao.updateById(sysEmployee);

                    //syslogin表
                    SysUserLoginEntity sysUser = new SysUserLoginEntity();
                    sysUser.setLoginId(sysEmployee.getEmpId());
                    sysUser.setEmpId(sysEmployee.getEmpId());
                    sysUser.setLoginPwd(sysEmployee.getPassword());
                    sysUser.setLoginCode(sysEmployee.getLoginCode());
                    sysUserLoginDao.updateById(sysUser);

                    //sysroleaccount表
                    SysRoleAccountsEntity sysRoleA = new SysRoleAccountsEntity();
                    sysRoleA.setId(sysEmployee.getEmpId());
                    sysRoleA.setLoginId(sysEmployee.getEmpId());
                    sysRoleA.setRoleId(sysEmployee.getRoleId());
                    sysRoleA.setModifiedBy(userView.getEmpName());
                    sysRoleAccountsDao.updateById(sysRoleA);
                } else {
                    return false;
                }
            } else {
                int count = sysEmployeeDao.ifHaveUserName(sysEmployee);
                System.out.println(count);
                if (count == 0) {
                    //SysEmployee表
                    sysEmployee.setEmpId(sysEmployeeDao.getNextId() + "");
                    sysEmployee.setOrgId("1");
                    Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2017-09-06");
                    sysEmployee.setStartDate(date);
                    date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-06-30");
                    sysEmployee.setEndDate(date);
                    sysEmployee.setPassword(new String(decoder.decodeBuffer(sysEmployee.getPassword())));//将base64加密的密码解成明文密码
                    sysEmployee.setPassword(DigestUtils.md5DigestAsHex(sysEmployee.getPassword().getBytes())); //md5加密
                    sysEmployeeDao.insert(sysEmployee);

                    //SysUserLogin表
                    SysUserLoginEntity sysUser = new SysUserLoginEntity();
                    sysUser.setLoginId(sysEmployee.getEmpId());
                    sysUser.setEmpId(sysEmployee.getEmpId());
                    sysUser.setLoginPwd(sysEmployee.getPassword());
                    sysUser.setLoginCode(sysEmployee.getLoginCode());
                    sysUserLoginDao.insert(sysUser);

                    //sysRoleAccount表
                    SysRoleAccountsEntity sysRoleA = new SysRoleAccountsEntity();
                    sysRoleA.setId(sysEmployee.getEmpId());
                    sysRoleA.setLoginId(sysEmployee.getEmpId());
                    sysRoleA.setRoleId(sysEmployee.getRoleId());
                    sysRoleA.setCreateTime(new Timestamp(new Date().getTime()));
                    sysRoleA.setModifiedBy(userView.getEmpName());
                    sysRoleA.setCreatedBy(userView.getEmpName());
                    sysRoleAccountsDao.insert(sysRoleA);
                } else {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public Result del(IdListVo idList) {
        try {
            if (idList != null && idList.getIdList().size() > 0) {
                sysEmployeeDao.deleteBatchIds(idList.getIdList());
                sysRoleAccountsDao.deleteBatchIds(idList.getIdList());
                sysUserLoginDao.deleteBatchIds(idList.getIdList());
                return new Result("删除人员成功！", ResultStatus.SUCCESS);
            } else {
                return new Result("未指定需要删除的记录！", ResultStatus.FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}